<template>
  <div class="student-manage-container">
    <div class="search-area">
      <el-card>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="学生姓名">
            <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" />
          </el-form-item>
          <el-form-item label="学号">
            <el-input v-model="searchForm.studentNumber" placeholder="请输入学号" />
          </el-form-item>
          <!-- <el-form-item label="班级">
            <el-select v-model="searchForm.class" placeholder="请选择班级" style="width: 160px">
              <el-option label="一班" value="一班" />
              <el-option label="二班" value="二班" />
              <el-option label="三班" value="三班" />
              <el-option label="四班" value="四班" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="table-area">
      <el-card>
        <el-table
          :data="students"
          border
          stripe
          style="width: 100%; max-height: 400px; overflow-y: auto;"
        >
              
          <el-table-column prop="studentNumber" label="学号" width="120" align="center" />
          <el-table-column prop="name" label="姓名"  align="center" />
          <el-table-column prop="studentImg" label="照片" width="80" align="center">
            <template #default="scope">
              <el-image  v-if="scope.row.studentImg" :src="scope.row.photo" fit="cover" style="width: 40px; height: 40px; border-radius: 50%;"></el-image>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="sex" label="性别" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.sex == 1" type="info">男</el-tag>
              <el-tag v-else type="danger">女</el-tag>
            </template>
          </el-table-column>
       
          <el-table-column prop="grade" label="年级" width="120" align="center" >
            <template #default="scope">
              {{ gradesMap[scope.row.grade] || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="contactWay" label="联系方式"  align="center" />
         
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" style="margin-left: 8px;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
// 使用vue-router的useRoute和useRouter  
import { useRoute, useRouter } from 'vue-router'
import * as studentApi from '@/api/studentManage'
// 模拟课程数据
const courses = ['高等数学', '线性代数', '计算机基础', '程序设计', '数据结构']

// 模拟学生数据生成函数
const generateMockData = () => {
  const data = []
  for (let i = 1; i <= 20; i++) {
    data.push({
      id: i,
      studentId: `2023${String(i).padStart(4, '0')}`,
      name: `学生${i}`,
      photo: `https://picsum.photos/seed/${i}/200/200`,
      gender: i % 2 === 0 ? '女' : '男',
      age: 18 + Math.floor(Math.random() * 4),
      class: `班级${Math.floor(i / 5) + 1}`,
      course: courses[Math.floor(Math.random() * courses.length)],
      contact: `13${Math.floor(Math.random() * 1000000000).toString().padStart(9, '0')}`,
      enrollmentDate: `2023-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      photo: `https://picsum.photos/seed/${i}/200/200`
    })
  }
  return data
}

let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)


const router = useRouter()

const gradesMap = {
  1: '初一',
  2: '初二',
  3: '初三',
  4: '高一',
  5: '高二',
  6: '高三',
}
// 查询学生列表
async function getStudents() {
  const res = await studentApi.studentList({
    studentName: searchForm.value.studentName,
    studentNumber: searchForm.value.studentNumber,
  }, currentPage.value, pageSize.value)
  if (res.code === 200) {
    students.value = res.rows || [];
    total.value = res.total
   
  }
}


const handleCurrentChange = (val) => {
  currentPage.value = val;
  getStudents()
}

const handleSizeChange = (val) => {
  currentPage.value = 1;
  pageSize.value = val;
  getStudents()
}






// 状态管理
let students = ref([])
let filteredStudents = ref([])
const searchForm = ref({
  studentName: '',
  studentNumber: '',
})

// 页面加载时生成并显示模拟数据
onMounted(() => {
  getStudents()
})

// 过滤逻辑
const handleSearch = () => {
  // filteredStudents.value = students.value.filter(student => {
  //   const nameMatch = student.name.includes(searchForm.value.studentName)
  //   const idMatch = student.studentId.includes(searchForm.value.studentNumber)
  //   return nameMatch && idMatch
  // })
  getStudents()
}

const handleReset = () => {
  searchForm.value = {
    studentName: '',
    studentNumber: '',
  }
  handleSearch()
}

const handleEdit = (id) => {
  // 跳转到编辑页面

  router.push({ path: '/studentManage/edit/' + id })
}

const handleAdd = () => {
  router.push({ path: '/studentManage/edit/new' })
}


const handleDelete = async (id) => {
  // 二次确认删除
  ElMessageBox.confirm('确定要删除该学生吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await studentApi.delStudent(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getStudents()
    }
  })
}


</script>

<style scoped>
.student-manage-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.table-area {
  height: calc(100vh - 220px);
}

.pagination {
  margin-top: 15px;
  text-align: right;
}
</style>